<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="请输入关键字" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">
            重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button type="success" @click="openRuleDialog()">新增</el-button>
            <el-button type="danger" :disabled="ruleIds.length === 0"
              @click="handleDeleteRule()"><i-ep-delete />批量删除</el-button>
            <el-button type="info" :disabled="ruleIds.length === 0"
              @click="openCheckDilalog()"><i-ep-delete />执行质检</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="ruleList" @selection-change="handleRuleSelectionChange" border stripe
        style="width: 100%" highlight-current-row>
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" width="100" align="center">

          <template #default="{ $index }">
            {{ (queryParams.page - 1) * queryParams.limit + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" width="200" header-align="center" align="center" label="规则名称">
        </el-table-column>
        <el-table-column prop="scene" width="150" header-align="center" align="center" label="场景">
        </el-table-column>
        <el-table-column prop="bz" width="300" header-align="center" align="center" label="备注">
        </el-table-column>
        <el-table-column prop="gmtCreate" width="200" header-align="center" align="center" label="创建时间">
        </el-table-column>

        <el-table-column label="操作" width="250" fixed="right" align="center">

          <template #default="scope">
            <el-button type="info" round
              @click="() => { openRuleDetailDialog(scope.row.id) }"><i-ep-edit />详情</el-button>
            <el-button type="primary" round @click="openRuleDialog(scope.row.id)"><i-ep-edit />编辑</el-button>
            <el-button type="danger" round @click="handleDeleteRule(scope.row.id)"><i-ep-delete />删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-if="total > 0" :page-sizes="[5, 10, 15, 20]" v-model:total="total" v-model:page="queryParams.page"
        v-model:limit="queryParams.limit" @pagination="handleQuery" @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle" layout="total, sizes, prev, pager, next, jumper"/>
    </el-card>

    <!-- 执行任务对话框 -->
    <el-dialog v-model="dialogTaskFormVisible" title="选择待检测的数据集" width="600px" append-to-body @close="closeTaskDialog">
      <el-alert title="执行检测任务需要一定时间，过一段时间再去检测结果页面查看" type="success" :closable="false" />
      <el-form ref="taskFormRef" :model="taskFormData" :rules="taskRules" label-width="120px">
        <el-form-item label="数据集" prop="selectedDataSetIds">
          <el-select v-model="taskFormData.selectedDataSetIds" multiple placeholder="Select" style="width: 240px">
            <el-option v-for="item in allDataSet" :key="item.fid" :label="item.frwnr" :value="item.fid" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleTaskSubmit">确 定</el-button>
          <el-button @click="closeTaskDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 规则详情 -->
    <el-dialog v-model="ruleDetailViewVisible" :width="'90%'">
      <el-descriptions title="规则基本信息" direction="vertical" :column="3" border>
        <el-descriptions-item label="名称">{{ ruleDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="场景">{{ ruleDetail.scene }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ ruleDetail.bz }}</el-descriptions-item>
      </el-descriptions>
      <el-divider>
        <h3 style="color: blueviolet;"><strong>逻辑信息</strong></h3>
      </el-divider>
      <el-descriptions direction="vertical" :column="2" border>
        <el-descriptions-item label="条件间逻辑关系">{{ ruleDetail.content }}</el-descriptions-item>
      </el-descriptions>

      <el-divider>
        <h3 style="color: blueviolet;"><strong>条件列表</strong></h3>
      </el-divider>

      <el-table :data="ruleDetail.conditionList" border stripe style="width: 100%" highlight-current-row>
        <el-table-column label="条件编号" width="150" align="center">

          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <!-- 显示算子列表 -->
        <el-table-column type="expand" stripe label="算子列表" width="300">

          <template #default="props">
            <h3>算子列表</h3>
            <el-table :data="props.row.operatorList">
              <el-table-column label="算子编号" width="100">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="类型" prop="type" width="150">

                <template #default="scope">
                  <el-tag v-if="scope.row.type == 1" type="warning">正则表达式</el-tag>
                  <el-tag v-if="scope.row.type == 2" type="success">包含关键词</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="内容" prop="content" width="100" />
            </el-table>
          </template>

        </el-table-column>
        <el-table-column prop="content" width="300" header-align="center" align="center" label="算子间逻辑关系">
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 规则表单弹窗 -->
    <el-dialog v-model="dialogRuleFormVisible" :title="dialogRuleType" width="1100px" append-to-body
      @close="closeRuleDialog">
      <el-form ref="RuleFormRef" label-position="top" :model="ruleFormData" :rules="rules"
        label-width="120px">
        <el-divider>
          <h3 style="color: blueviolet;"><strong>基本信息</strong></h3>
        </el-divider>
        <el-form-item label="规则名称:" prop="name">
          <el-input v-model="ruleFormData.name" placeholder="规则名称"></el-input>
        </el-form-item>
        <el-form-item label="场景:" prop="sceneId">
          <el-select v-model="ruleFormData.sceneId" filterable placeholder="请选择场景" style="width: 240px">
            <el-option v-for="item in sceneList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="复核页面显示备注:" prop="bz">
          <el-input v-model="ruleFormData.bz" placeholder="输入备注"></el-input>
        </el-form-item>
        <el-divider>
          <h3 style="color: blueviolet;"><strong>逻辑信息</strong></h3>
        </el-divider>
        <el-form-item label="条件间逻辑关系:" prop="content">
          <el-input v-model="ruleFormData.content" placeholder="输入条件间逻辑关系"></el-input>
        </el-form-item>

      </el-form>
      <el-divider>
        <h3 style="color: blueviolet;"><strong>条件列表</strong></h3>
      </el-divider>

      <div>
        <el-button type="success" @click="openConditionDialog()">新增</el-button>
        <el-button type="danger" :disabled="conditionIds.length === 0"
          @click="handleDeleteCondition()"><i-ep-delete />批量删除</el-button>
      </div>
      <el-table v-loading="conditionListLoading" :data="conditionList.value"
        @selection-change="handleConditionSelectionChange" border stripe style="width: 100%" highlight-current-row>
        <el-table-column type="selection"  width="50" align="center" />
        <el-table-column label="条件编号" width="150" align="center">

          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <!-- 显示算子列表 -->
        <el-table-column type="expand" stripe label="算子列表" width="300">

          <template #default="props">
            <h3>算子列表</h3>
            <el-table :data="props.row.operatorList">
              <el-table-column label="算子编号" width="100">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="类型" prop="type" width="150">

                <template #default="scope">
                  <el-tag v-if="scope.row.type == 1" type="warning">正则表达式</el-tag>
                  <el-tag v-if="scope.row.type == 2" type="success">包含关键词</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="内容" prop="content" width="100" />
            </el-table>
          </template>

        </el-table-column>
        <el-table-column prop="content" width="300" header-align="center" align="center" label="算子间逻辑关系">
        </el-table-column>

        <el-table-column label="操作">

          <template #default="scope">
            <el-button type="primary" link @click="openConditionDialog(scope.row.id)"><i-ep-edit />编辑</el-button>
            <el-button type="danger" link @click="handleDeleteCondition(scope.row.id)"><i-ep-delete />删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleRuleSubmit">确 定</el-button>
          <el-button @click="closeRuleDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 条件 表单弹窗 -->
    <el-dialog v-model="dialogConditionFormVisible" :title="dialogConditionType" width="600px" append-to-body
      @close="closeConditionDialog">
      <el-form ref="conditionFormRef" :model="conditionFormData" :rules="conditionRules" label-width="120px">
        <el-form-item label="算子间逻辑关系" prop="content">
          <el-input v-model="conditionFormData.content" placeholder="请输入算子间逻辑关系"></el-input>
        </el-form-item>
      </el-form>
      <el-divider>
        <h3 style="color: blueviolet;"><strong>算子列表</strong></h3>
      </el-divider>
      <div>
        <el-button type="success" @click="openOperatorDialog()">新增</el-button>
        <el-button type="danger" :disabled="operatorIds.length === 0"
          @click="handleDeleteOperator()"><i-ep-delete />批量删除</el-button>
      </div>
      <el-table v-loading="operatorListloading" :data="operatorList.value"
        @selection-change="handleOperatorSelectionChange" border stripe style="width: 100%" highlight-current-row>
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="算子编号" width="150" align="center">

          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="type" width="150" header-align="center" align="center" label="类型">

          <template #default="scope">
            <el-tag v-if="scope.row.type == 1" type="warning">正则表达式</el-tag>
            <el-tag v-if="scope.row.type == 2" type="success">包含关键词</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" width="200" header-align="center" align="center" label="内容">
        </el-table-column>

        <el-table-column label="操作" width="100">

          <template #default="scope">
            <el-button type="primary" link @click="openOperatorDialog(scope.row.id)"><i-ep-edit />编辑</el-button>
            <el-button type="danger" link @click="handleDeleteOperator(scope.row.id)"><i-ep-delete />删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConditionSubmit">确 定</el-button>
          <el-button @click="closeConditionDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 算子 表单弹窗 -->
    <el-dialog v-model="dialogOperatorFormVisible" :title="dialogOperatorType" width="800px" append-to-body
      @close="closeOperatorDialog">
      <el-form ref="operatorFormRef" :model="operatorFormData" :rules="operatorRules" label-width="120px">
        <el-form-item label="菜单类型:" prop="type">
          <el-radio-group v-model="operatorFormData.type">
            <el-radio :label="1">正则表达式</el-radio>
            <el-radio :label="2">包含关键词</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="算子内容:" prop="content" v-if="operatorFormData.type == 1">
          <el-input v-model="operatorFormData.content" placeholder="算子内容"></el-input>
        </el-form-item>
        <el-form-item label="关键词:" prop="sceneId" v-else>
          <el-select v-model="operatorFormData.selectedKeywords" :remote-method="remoteMethod" multiple collapse-tags
            collapse-tags-tooltip filterable remote :max-collapse-tags="4" :loading="selectKeywordLoading"
            placeholder="请选择关键词" style="width: 240px">
            <el-option v-for="item in allKeyword" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleOperatorSubmit">确 定</el-button>
          <el-button @click="closeOperatorDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getListApi,
  getInfoApi,
  deleteApi,
  saveApi,
  updateApi,
  getDataSetApi,
  checkApi,
} from "@/api/qualityInspect/rule.js";
import { getAllApi } from "@/api/qualityInspect/scene.js";
import { getListApi as getKeywordList } from "@/api/qualityInspect/keyword.js";
import { saveApi as saveOperatorApi, updateApi as updateOperatorApi, deleteApi as deleteOperatorApi, getInfoApi as getOperatorInfoApi } from "@/api/qualityInspect/operator.js";
import { saveApi as saveConditionApi, updateApi as updateConditionApi, deleteApi as deleteConditionApi, getInfoApi as getConditionInfoApi } from "@/api/qualityInspect/condition.js";
import { reactive, ref } from "vue";
import {
  ElForm,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElTable,
} from 'element-plus'

// 分页查询参数接口
interface SceneQuery {
  keywords?: string;
  page?: number;
  limit?: number;
}

// 列表接口
interface RulePageVo {
  id?: number;
  name?: string;
  scene?: string;
  bz?: string;
  gmtCreate?: Date;
}
/* // 算子接口
interface OperatorVo {
  id?: number;
  type?: number;
  scene?: string;
}

// 条件接口
interface ConditionVo {
  id?: number;

} */


// 添加修改规则表单数据接口
interface RuleForm {
  id?: number;
  name?: string;
  sceneId?: number;
  bz?: string;
  content?: string;
}
// 添加修改条件表单数据接口
interface ConditionForm {
  id?: number;
  content?: string;
}
// 添加修改算子表单数据接口
interface OperatorForm {
  id?: number;
  type?: number;
  content?: string;
  selectedKeywords?: [];
}
// 任务表单数据接口
interface TaskForm {
  selectedDataSetIds?: [];
  selectedRuleIds?: [];
}

const queryFormRef = ref(ElForm); // 查询表单
const RuleFormRef = ref(ElForm);
const conditionFormRef = ref(ElForm);
const operatorFormRef = ref(ElForm);
const taskFormRef = ref(ElForm);
const sceneList = ref([]);// 场景列表
const allKeyword = ref([]);
const loading = ref(false);
const selectKeywordLoading = ref(false);
const operatorListloading = ref(false);
const conditionListLoading = ref(false);
const ruleIds = ref([]); // 被选中的id集合
const conditionIds = ref([]); // 被选中的id集合
const operatorIds = ref([]); // 被选中的id集合
const total = ref(0);
const dialogRuleFormVisible = ref(false)
const dialogConditionFormVisible = ref(false)
const dialogOperatorFormVisible = ref(false)
const dialogTaskFormVisible = ref(false)
const ruleDetailViewVisible = ref(false)
const dialogRuleType = ref('')
const dialogConditionType = ref('')
const dialogOperatorType = ref('')
const queryParams = reactive<SceneQuery>({
  page: 1,
  limit: 10,
});

const ruleList = ref<RulePageVo[]>();
let operatorList = reactive({ value: [] });
let conditionList = reactive({ value: [] });
const ruleFormData = reactive<RuleForm>({});
const conditionFormData = reactive<ConditionForm>({});
const operatorFormData = reactive<OperatorForm>({});
const taskFormData = reactive<TaskForm>({});
const allDataSet = ref([]);
const ruleDetail = ref({
  conditionList: []
});


/**
 * 打开规则详情弹窗
 */
const openRuleDetailDialog = (id?: number) => {

  // 获取规则详情
  getInfoApi(id).then(({ data }) => {
    ruleDetail.value = data
  })

  ruleDetailViewVisible.value = true

}

const getAllDataSet = () => {
  getDataSetApi().then(({ data }) => {
    allDataSet.value = data
  })
}


const checkRuleContent = (rule: any, value: any, callback: any) => {
  if (value === '' || value === undefined) {
    return callback(new Error('必需输入条件间的关系'))
  } else {
    // 判断正则表达式格式是否正确
    if (!isValidLogicExpression(value)) {
      return callback(new Error('表达式不正确'))
    }

    // 提取输入的所有条件编号，判断是否存在条件列表中
    return isValidNumbers(value, conditionList.value.length) ? callback() : callback(new Error('内容中，有不存在的条件编号'))

  }
}
const taskRules = reactive({
  selectedDataSetIds: [
    { required: true, message: '很选择选择待检测的数据集', trigger: 'blur' }
  ],
})

const rules = reactive({
  name: [
    { required: true, message: '规则名称不能为空', trigger: 'blur' }
  ],
  content: [
  { required: true, message: '逻辑间关系不能为空', trigger: 'blur' },
    { validator: checkRuleContent, trigger: 'blur' }
  ]
});
const isValidNumbers = (expression, max) => {
  const pattern = /\d+/g; // 正则表达式，匹配一个或多个数字，'g'标志表示全局搜索  
  let match;
  while ((match = pattern.exec(expression)) !== null) {
    // 尝试将匹配的字符串转换为整数  
    const num = parseInt(match[0], 10);

    // 检查转换是否成功，并且数字是正整数  
    if (!(!isNaN(num) && num > 0 && num <= max)) {
      return false
    }
  }
  return true;
}


const isValidLogicExpression = (input) => {
   // 定义正则表达式，匹配只包含数字、&&、||、(、)、! 的字符串  
   const regex = /^[0-9&&\|\(\)!]+$/;  
      // 使用正则表达式的 test 方法检查字符串是否匹配  
  return  regex.test(input);  
  
}

const checkConditionContent = (rule: any, value: any, callback: any) => {
  if (value === '' || value === undefined) {
    return callback(new Error('必需输入算子间的关系'))
  } else {
    // 判断正则表达式格式是否正确
    if (!isValidLogicExpression(value)) {
      return callback(new Error('表达式不正确'))
    }

    // 提取输入的所有算子编号，判断是否存在算子列表中
    return isValidNumbers(value, operatorList.value.length) ? callback() : callback(new Error('内容中，有不存在的算子编号'))

  }
}

const conditionRules = reactive({
  content: [
    { validator: checkConditionContent, trigger: 'blur' }
  ]
});

// 判断是否为正则表达式
const isRegExp = (pattern) => {
  // TODO 判断一个字符串是否为正则表达式
  return true
}

const checkOperatorContent = (rule: any, value: any, callback: any) => {
  // 算子内容为正则表达式类型时
  if (operatorFormData.type == 1) {
    if (value === '' || value === undefined) {
      return callback(new Error('必需输入正则表达式'))
    } else {
      isRegExp(operatorFormData.content) ? callback() : callback(new Error('输入的正则表达式存在语法错误'))
    }
  } else {
    callback()
  }
}
const operatorRules = reactive({
  type: [{ required: true, message: '类型必需选择', trigger: 'blur' }],
  content: [{ validator: checkOperatorContent, trigger: 'blur' }],
});

// 打开任务对话框
const openCheckDilalog = () => {
  getAllDataSet()
  dialogTaskFormVisible.value = true
  taskFormData.selectedRuleIds = ruleIds.value
}


// 模糊查询关键词
const remoteMethod = (query: string) => {
  selectKeywordLoading.value = true
  getKeywordList({
    page: 1,
    limit: 100,
    keywords: query
  }).then(({ data }) => {
    allKeyword.value = data.list;
  }).finally(() => {
    selectKeywordLoading.value = false;
  });
}

/**
 * 查询
 */
const handleQuery = () => {
  loading.value = true;
  getListApi(queryParams) // 获取列表
    .then(({ data }) => {
      ruleList.value = data.list;
      total.value = data.totalCount;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  handleQuery();
}

/**
 * 修改每页数
 */
const sizeChangeHandle = (val: number) => {
  queryParams.limit = val
  queryParams.page = 1
  handleQuery()
}

/**
 * 修改当前页
 */
const currentChangeHandle = (val: number) => {
  queryParams.page = val
  handleQuery()
}

/**
 * 行checkbox change事件
 */
const handleRuleSelectionChange = (selection: any) => {
  ruleIds.value = selection.map((item: any) => item.id);
}
/**
 * 行checkbox change事件
 */
const handleConditionSelectionChange = (selection: any) => {
  conditionIds.value = selection.map((item: any) => item.id);
}
/**
 * 行checkbox change事件
 */
const handleOperatorSelectionChange = (selection: any) => {
  operatorIds.value = selection.map((item: any) => item.id);
}


/**
 * 打开添加修改规则弹窗
 */
const openRuleDialog = (idId?: number) => {
  if (idId) {
      dialogRuleType.value = "修改规则"
    getInfoApi(idId).then(({ data }) => {
      // 获取所有场景
      getAllApi().then(({ data }) => {
        sceneList.value = data
      })
      Object.assign(ruleFormData, data);
      conditionList.value = data.conditionList
    });
  } else {
    dialogRuleType.value = "新增规则";

    // 获取所有场景
    getAllApi().then(({ data }) => {
      sceneList.value = data
    })
  }

  dialogRuleFormVisible.value = true;
}
/**
 * 打开添加修改条件弹窗
 */
const openConditionDialog = (idId?: number) => {
  if (idId) {
    dialogConditionType.value = "修改条件";
    getConditionInfoApi(idId).then(({ data }) => {
      conditionFormData.id = data.id
      conditionFormData.content = data.content
      operatorList.value = data.operatorList
    });
  } else {
    dialogConditionType.value = "新增条件";
  }
  dialogConditionFormVisible.value = true;
}
/**
 * 打开添加修改算子弹窗
 */
const openOperatorDialog = (idId?: number) => {

  // 获取所有关键词
  remoteMethod(null);

  if (idId) {
    dialogOperatorType.value = "修改算子";
    getOperatorInfoApi(idId).then(({ data }) => {
      Object.assign(operatorFormData, data);
    });
  } else {
    dialogOperatorType.value = "新增算子";
  }

  dialogOperatorFormVisible.value = true;
}

/**
 * 关闭任务对话框
 */
const closeTaskDialog = () => {
  dialogTaskFormVisible.value = false
  resetTaskForm()
}

/**
 * 关闭规则弹窗
 */
const closeRuleDialog = () => {
  dialogRuleFormVisible.value = false;
  resetRuleForm();
}
/**
 * 关闭条件弹窗
 */
const closeConditionDialog = () => {
  dialogConditionFormVisible.value = false;
  resetConditionForm();
}
/**
 * 关闭算子弹窗
 */
const closeOperatorDialog = () => {
  dialogOperatorFormVisible.value = false;
  resetOperatorForm();
}

/**
 * 重置任务表单
 */
const resetTaskForm = () => {

  // 清空校验
  taskFormRef.value.clearValidate()
  // 清空表单数据
  taskFormData.selectedDataSetIds = []
  taskFormData.selectedRuleIds = []

}

/**
 * 重置规则表单
 */
const resetRuleForm = () => {
  RuleFormRef.value.resetFields();
  RuleFormRef.value.clearValidate();

  ruleFormData.id = undefined;

  conditionList.value = [];

}
/**
 * 重置条件表单
 */
const resetConditionForm = () => {
  conditionFormRef.value.clearValidate();

  conditionFormData.id = undefined;
  conditionFormData.content = undefined;
  operatorList.value = [];

}
/**
 * 重置算子表单
 */
const resetOperatorForm = () => {
  // 清空
  operatorFormData.content = undefined
  operatorFormData.type = 1
  operatorFormData.selectedKeywords = []
  operatorFormData.id = undefined;
  operatorFormRef.value.clearValidate();

}

/**
 * 任务表单提交
 */
const handleTaskSubmit = () => {
  taskFormRef.value.validate((valid: any) => {
    if (valid) {

      // 提交检测任务
      checkApi(taskFormData)

      ElMessage.success("提交成功！！！");
      closeTaskDialog();

    }
  });
}

/**
 *  规则表单提交
 */
const handleRuleSubmit = () => {
  RuleFormRef.value.validate((valid: any) => {
    if (valid) {
      const ruleId = ruleFormData.id;
      loading.value = true;

      // 将条件序号替换成条件id,再覆盖到content中  
      ruleFormData.content = replaceNumWithId(ruleFormData.content, conditionList.value)

      // 更新操作
      if (ruleId) {
        updateApi(ruleFormData)
          .then(() => {
            ElMessage.success("修改成功");
            closeRuleDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        saveApi(ruleFormData) // 添加操作
          .then(() => {
            ElMessage.success("新增成功");
            closeRuleDialog();
            resetQuery();

          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
/**
 *  条件表单提交
 */
const handleConditionSubmit = () => {
  conditionFormRef.value.validate((valid: any) => {
    if (valid) {
      const conditionId = conditionFormData.id;
      conditionListLoading.value = true;

      // 更新操作
      if (conditionId) {
        // 将算子序号替换成算子id,再覆盖到content中 
        conditionFormData.content = replaceNumWithId(conditionFormData.content, operatorList.value)
        updateConditionApi(conditionFormData)
          .then(({ data }) => {
            ElMessage.success("修改成功");
            closeConditionDialog();

            // 将新记录修改更新到条件列表
            for (let i = 0; i < conditionList.value.length; i++) {
              if (conditionList.value[i].id == data.id) {
                conditionList.value[i] = data
                break
              }
            }

          })
          .finally(() => (conditionListLoading.value = false));
      } else {
        // 将算子序号替换成算子id,再覆盖到content中 
        conditionFormData.content = replaceNumWithId(conditionFormData.content, operatorList.value)
        saveConditionApi(conditionFormData) // 添加操作
          .then(({ data }) => {
            ElMessage.success("新增成功");
            closeConditionDialog();

            conditionList.value.push(data)

          })
          .finally(() => (conditionListLoading.value = false));
      }
    }
  });
}
/**
 *  算子表单提交
 */
const handleOperatorSubmit = () => {
  operatorFormRef.value.validate((valid: any) => {
    if (valid) {
      const operatorId = operatorFormData.id;
      operatorListloading.value = true;

      // 更新操作
      if (operatorId) {
        updateOperatorApi(operatorFormData)
          .then(({ data }) => {
            ElMessage.success("修改算子成功");
            closeOperatorDialog();

            // 将新记录修改更新到算子列表
            for (let i = 0; i < operatorList.value.length; i++) {
              if (operatorList.value[i].id == data.id) {
                operatorList.value[i] = data
                break
              }
            }

          })
          .finally(() => (operatorListloading.value = false));
      } else {
        saveOperatorApi(operatorFormData) // 添加操作
          .then(({ data }) => {
            ElMessage.success("新增算子成功");
            closeOperatorDialog();

            // 添加新记录到算子列表
            operatorList.value.push(data)

          })
          .finally(() => (operatorListloading.value = false));
      }
    } else {
      console.log("算子表单验证失败！！！！！！！！！！")
    }
  });
}


// 注意：条件编号只能是个位数，即最多9个条件
/* const replaceNumWithId = (logic, list)=> {  
    let result = '';  
    let numStack = []; // 存储数字的栈  
  
    for (let i = 0; i < logic.length; i++) {  
        let char = logic[i];  
        if (Number.isInteger(Number(char))) { // 如果当前字符是数字  
            numStack.push(Number(char)); // 将数字推入栈中  
        } else if (char === '(') { // 如果当前字符是左括号  
            result += char; // 将左括号添加到结果中  
        } else if (char === ')') { // 如果当前字符是右括号  
            let num = Number(numStack.pop()); // 从栈中弹出数字  
            result += list[num-1].id; // 在结果中添加数字对应的id  
            result += char; // 将右括号添加到结果中  
        } else { // 如果当前字符是逻辑运算符或逻辑非  
            while (numStack.length > 0 && !Number.isInteger(Number(result[result.length - 1]))) {  
              result += list[numStack.pop()-1].id; // 将栈顶的数字对应的id添加到结果中，直到栈为空或遇到数字
            }  
            result += char; // 将当前字符添加到结果中  
        }  
    }  
  
    while (numStack.length > 0) { // 将栈中剩余的数字对应的id添加到结果中  
        result += list[Number(numStack.pop())-1].id;  
    }  
  
    return result;  
} */

const replaceNumWithId = (logic, list) => {
  let result = '';
  let numStack = []; // 存储数字的栈  

  for (let i = 0; i < logic.length; i++) {
    let c = logic.charAt(i);
    if (c >= '0' && c <= '9') { // 如果当前字符是数字  
      let num = 0;
      let j = i;
      while (j < logic.length && logic.charAt(j) >= '0' && logic.charAt(j) <= '9') {
        num = num * 10 + (logic.charCodeAt(j) - '0'.charCodeAt(0));
        j++;
      }
      i = j - 1; // 跳过已处理的数字部分  
      numStack.push(num); // 将数字推入栈中  
    } else if (c === '(') { // 如果当前字符是左括号  
      result += c; // 将左括号添加到结果中  
    } else if (c === ')') { // 如果当前字符是右括号  
      let num = Number(numStack.pop()); // 从栈中弹出数字  
      result += list[num - 1].id; // 在结果中添加数字对应的id  
      result += c; // 将右括号添加到结果中  
    } else { // 如果当前字符是逻辑运算符或逻辑非  
      if (result === '') { // 检查result是否为空  
        if (numStack.length >= 1) {
          result += list[numStack.pop() - 1].id;
        }
      } else {
        while (numStack.length >= 1 && isNaN(result.charAt[result.length - 1])) {
          result += list[numStack.pop() - 1].id; // 将栈顶的数字对应的id添加到结果中，直到栈为空或遇到数字  
        }
      }
      result += c; // 将当前字符添加到结果中  
    }
  }

  while (numStack.length >= 1) { // 将栈中剩余的数字对应的id添加到结果中  
    result += list[numStack.pop() - 1].id;
  }

  return result;
}

/**
 * 删除规则
 */
const handleDeleteRule = (id?: number) => {
  let Ids = []
  // 单个删除
  if (id != null) {
    Ids.push(id)
  } else {
    // 批量删除
    if (!ruleIds) {
      ElMessage.warning("请勾选删除项");
      return;
    }
    Ids = ruleIds.value
  }


  ElMessageBox.confirm("确认删除选中的记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteApi(Ids).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}
/**
 * 删除条件
 */
const handleDeleteCondition = (id?: number) => {
  let Ids = []
  // 单个删除
  if (id != null) {
    Ids.push(id)
  } else {
    // 批量删除
    if (!conditionIds) {
      ElMessage.warning("请勾选删除项");
      return;
    }
    Ids = conditionIds.value
  }


  ElMessageBox.confirm("确认删除选中的记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteApi(Ids).then(() => {
      ElMessage.success("删除成功");

      // 遍历删除列表中id出现Ids的在记录
      let saveRecord = []
      let set = new Set(Ids);

      for (let i = 0; i < conditionList.value.length; i++) {
        if (!set.has(conditionList.value[i].id)) {
          saveRecord.push((conditionList.value[i]));
        }
      }
      conditionList.value = []
      // 更新算子列表数据
      for (let i = 0; i < saveRecord.length; i++) {
        conditionList.value.push(saveRecord[i])
      }
    });
  });
}
/**
 * 删除算子
 */
const handleDeleteOperator = (id?: number) => {
  let Ids = []
  // 单个删除
  if (id != null) {
    Ids.push(id)
  } else {
    // 批量删除
    if (!operatorIds) {
      ElMessage.warning("请勾选删除项");
      return;
    }
    Ids = operatorIds.value
  }


  ElMessageBox.confirm("确认删除选中的记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteOperatorApi(Ids).then(() => {
      ElMessage.success("删除成功");

      // 遍历删除列表中id出现Ids的在记录
      let saveRecord = []

      let set = new Set(Ids);
      for (let i = 0; i < operatorList.value.length; i++) {
        if (!set.has(operatorList.value[i].id)) {
          saveRecord.push((operatorList.value[i]));
        }


      }
      operatorList.value = []
      // 更新算子列表数据
      for (let i = 0; i < saveRecord.length; i++) {
        operatorList.value.push(saveRecord[i])
      }

    });
  });
}


handleQuery(); // 初始化列表数据

</script>
